package com.icangya.admin;

import com.alibaba.fastjson.JSONObject;
import com.icangya.DAO.IUserFootDAO;
import com.icangya.Utils.ImageUtils;
import com.icangya.Utils.JSONUtils;
import com.icangya.Utils.MD5Util;
import com.icangya.Utils.UploadUtils;
import com.icangya.Value.StaticValue;
import com.icangya.domain.Admin;
import com.icangya.domain.AgentImage;
import com.icangya.domain.User;
import com.icangya.service.IAdminUserService;
import com.icangya.service.IAgentService;
import com.icangya.service.IFootUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.icangya.Value.StaticValue.ADMIN_USER_SESSION;

@CrossOrigin
@RestController
@RequestMapping(path = "/admin/agent/")
public class AgentController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ImageUtils imageUtils = ImageUtils.getIstance();

    @Autowired
    private IAgentService iAgentService;
    @Autowired
    private IFootUserService iFootUserService;
    @Autowired
    private IUserFootDAO iUserFootDAO;
    @Autowired
    private IAdminUserService iAdminUserService;


    /**
     * 查询用户，为其添加代理权限
     * @param uid
     * @param session
     * @return
     */
    @RequestMapping(value = "getAgentUser", method = RequestMethod.GET)
    public JSONObject getAgentUser(@RequestParam long uid,HttpSession session){
        Admin admin= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
        if(admin.getUid()==uid)
            return JSONUtils.getRoot(1, "fail", "不能为自己设置代理");

        if(iAgentService.checkAgentUser(uid))
            return JSONUtils.getRoot(1, "fail", "该用户已经是代理了");

//        User user=iUserFootDAO.checkUserById(uid,admin.getUid());
//        if(user==null)
//            return JSONUtils.getRoot(1, "fail", "该用户名不在您的团队中");
//        JSONObject jsonObject=iAdminUserService.checkUserById(uid,80);//测试
        JSONObject jsonObject=iAdminUserService.checkUserById(uid,admin.getUid());
        if(jsonObject!=null)
            return JSONUtils.getRoot(0,"success",jsonObject);
        return JSONUtils.getRoot(1,"fail","该用户名不在您的团队中");

    }


    /**
     *增加代理
     * @param name 登录名
     * @param passWord  密码
     * @param uid 游戏id
     * @return
     */
    @RequestMapping(value = "addAgent", method = RequestMethod.GET)
    public JSONObject addAgent(@RequestParam String name, @RequestParam String passWord, @RequestParam long uid, HttpSession session){


        //先判断该用户名是否已存在
        if (iAgentService.checkAgentName(name)) {
            return JSONUtils.getRoot(1, "fail", "用户名已存在");
        }
        if(iAgentService.checkAgentUser(uid)) {
            return JSONUtils.getRoot(1, "fail", "该用户已经是代理了");
        }
          Admin loginUser= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息

        if(loginUser.getUserLevel()>=5) {
            return JSONUtils.getRoot(1, "fail", "该用户没有权限开代理");
        }
        Admin user=iAgentService.getAdminById(loginUser.getId());
//        Admin user=iAgentService.getAdminById(1L);//测试登录的用户


        //正则匹配密码为4-10位的数字
        Pattern p = Pattern.compile("(\\d{4,10})");
        Matcher m = p.matcher(name);

        //正则匹配密码为6-12位的数字和字母
        Pattern p1 = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$");
        Matcher m1 = p1.matcher(passWord);

        if (m.matches() && m1.matches()) {
            //密码加密(规则：密码+proxy_key，使用md5加一次密)
            passWord = MD5Util.toMD5(passWord + StaticValue.PROXY_KEY).toUpperCase();

        }else{
//            1，密码不能全部是数字
//            2，密码不能全部是字母
//            3，密码必须是数字或字母
            return JSONUtils.getRoot(1,"fail","账号或密码长度不符合，账号的长度是4-10的数字，密码的长度为6-12位的数字加字母");
        }

        if(user==null) {
            return JSONUtils.getRoot(1, "fail", "用户为空，请重新登录");
        }
        //登录后台的账号，密码，用户游戏id
        // 修改该用户的proxyId为自己的游戏id
        //将添加的代理加到代理明细表中
        Admin admin = new Admin();
        admin.setUserName(name);
        admin.setPassWord(passWord);
        admin.setGradeId(1);//设置管理员
        admin.setUid(uid);
        admin.setUserId(user.getId());
        admin.setUserLevel(user.getUserLevel()+1);//树结构的层级数  父节点的层级加一
        admin.setCreateTime(new Timestamp(new Date().getTime()));
        //一、 左下标值= 父节点的右下标值
        //右下标值=父节点的右下标值+1
        //设置新节点左下标
        admin.setLeftNum(user.getRightNum());//父节点的右下标值
        admin.setRightNum(user.getRightNum() + 1);//父节点的右下标值+1
        admin.setCreateTime(new Timestamp(new Date().getTime()));

        //添加代理
        Admin use=iAgentService.addAgentUser(admin);
        if(use !=null){//添加成功之后

            //重新生成代理推广二维码
            setQrCode(use.getUid());

            // 二、更新：大于等于新增节点的左下标值的右下标值都加2
            iAgentService.updateAgentRightNum(use.getLeftNum(),use.getId());
            //三、更新：大于等于新增节点的右下标值的左下标值都加2
            iAgentService.updateAgentLeftNum(use.getRightNum(),use.getId());

            //修改所有粉丝的代理id为指定id
            changProxyId(use.getUid());


            return JSONUtils.getRoot(0,"success","添加成功");
        }

        return JSONUtils.getRoot(2,"fail","添加失败,请重新加载!!!!");
    }

    /**
     * 查询所有下级代理明细
     * @return
     */
    @RequestMapping(value = "findLowerAgent", method = RequestMethod.GET)
    public JSONObject findLowerAgent(@RequestParam String startTime,@RequestParam String endTime,@RequestParam int startPage,HttpSession session){


        logger.info(startTime+"开始时间 start..................end="+endTime);
        logger.info(endTime+"开始时间 end..................");
        if(startTime ==null || startTime=="" )
            return JSONUtils.getRoot(1,"fail","开始时间未设置");
        if(endTime=="")
            return JSONUtils.getRoot(1,"fail","结束时间未设置");

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//

       // String date=sdf.format(new Date(Long.valueOf(startTime+"000")));

        Date start= new Date();
        Date end= new Date();
        try {
            start = sdf.parse(startTime);
            end = sdf.parse(endTime);
            System.out.println(start.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Timestamp sTime=new Timestamp(start.getTime());
        Timestamp eTime=new Timestamp(end.getTime());

          Admin loginUser= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
        Admin user=iAgentService.getAdminById(loginUser.getId());
//        Admin user=iAgentService.getAdminById(1L);//测试登录的用户

        JSONObject jsonObject=iAgentService.getLowerAgent(user.getId(),sTime,eTime,startPage);
        if(jsonObject!=null)
        return JSONUtils.getRoot(0,"success",jsonObject);
        return JSONUtils.getRoot(1,"fail",null);
    }

    //转换时间
    public Date getDate(String date){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//
        Date start= new Date();
        try {
            start = sdf.parse(date);
            logger.info(start.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return start;
    }


    /**
     * 取消授权代理
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteAgent")
    public JSONObject deleteAgent(@RequestParam long id,HttpSession session){

        //  Admin user= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息

        //取消授权之后他的粉丝的proxyId改为上级的授权代理proxyId
        //删除之后将该代理下的所有粉丝修改为系统的粉丝
        List<Object[]> list=iAgentService.deleteAgent(id);
        if(list==null)
            return JSONUtils.getRoot(0,"success","已取消授权");

        //取消之后将用户团队的推广二维码更新
        for(int i=0;i<list.size();i++){
            Object[] obj=list.get(i);
            if(obj[0]==null)
                continue;
            setQrCode(Long.parseLong(obj[0].toString()));
        }

        return JSONUtils.getRoot(1,"fail","取消授权失败");
    }

    /**
     * 根据id查询代理信息
     * @param id
     * @return
     */
    @RequestMapping(value = "getAgentById")
    public JSONObject getAgentById(@RequestParam long id,@RequestParam String startTime,@RequestParam String endTime,HttpSession session){
        logger.info("getAgentById..........");
        logger.info(startTime+"时间 start..................end="+endTime);

        if(startTime ==null || startTime=="" ) {
            return JSONUtils.getRoot(1, "fail", "开始时间未设置");
        }
        if(endTime==""){
            return JSONUtils.getRoot(1,"fail","结束时间未设置");
        }

        try {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//
            Date start= sdf.parse(startTime);;
            Date end=  sdf.parse(endTime);

            Timestamp sTime=new Timestamp(start.getTime());
            Timestamp eTime=new Timestamp(end.getTime());
              Admin loginUser= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
            Admin user=iAgentService.getAdminById(loginUser.getId());
    //        Admin user=iAgentService.getAdminById(1L);//测试登录的用户
            JSONObject jsonObject=  iAgentService.getAgentById(id,sTime,eTime,user.getLeftNum(),user.getRightNum());
              if(jsonObject!=null) {
                  return JSONUtils.getRoot(0, "success", jsonObject);
              }
            return JSONUtils.getRoot(1,"fail","该代理用户不存在");
        } catch (ParseException e) {
            return JSONUtils.getRoot(1, "fail", "");
        }
    }


    /**
     * 代理客服图
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "setAgentImg")
    public JSONObject setAgentImg(HttpSession session,HttpServletRequest request, HttpServletResponse response, MultipartFile file) {

        Admin admin= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
//        Admin user=iAgentService.getAdminById(loginUser.getId());
        String path="agentImg/";

      String agentImgUrl= UploadUtils.uploadImg(path,request,file);
        if(agentImgUrl==null)
        return JSONUtils.getRoot(1,"fail","图片上传失败");

        AgentImage agentImage=new AgentImage(agentImgUrl,admin.getUid());
//        AgentImage agentImage=new AgentImage(agentImgUrl,1);//测试
        AgentImage agent= iAgentService.addAgentImage(agentImage);
        if(agent!=null) {
            try {
//                response.sendRedirect("http://192.168.0.121:8020/football/src/main/resources/static/hAdmin/code.html");
                response.sendRedirect("hAdmin/code.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return JSONUtils.getRoot(0, "success", agent);
        }
        return JSONUtils.getRoot(1,"fail","发布失败");
    }


    /**
     * 获取代理客服图
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "getAgentImg")
    public JSONObject getAgentImg(HttpSession session,HttpServletRequest request, HttpServletResponse response, MultipartFile file) {

        Admin admin= (Admin) session.getAttribute(ADMIN_USER_SESSION);//获取登录后台的用户信息
        AgentImage agent= iAgentService.getAgentImage(admin.getUid());
//        AgentImage agenter= iAgentService.getAgentImage(1);
        if(agent!=null)
            return JSONUtils.getRoot(0, "success", agent);
        return JSONUtils.getRoot(1,"fail","发布失败");

    }














    //子节点
    List<User> childUser = new ArrayList<User>();

    /**
     * 修改所有粉丝的代理id为指定id
     * @param uid
     * @return
     */
//    @RequestMapping(value = "changProxyId")
    public JSONObject changProxyId (long uid) {
        List<User> userList = iFootUserService.findAllUser();
        List<User> userList2 = new ArrayList<User>();
        treeUserList(userList,uid);

        logger.info(childUser.size()+"============");
        for (User user: childUser){
           // User user = userList2.get(i);
            user.setProxyId(uid);

            iUserFootDAO.updateProxyId(user.getId(),uid);

            //重新生成用户推广二维码
            setQrCode(user.getId());

            System.out.println(user.getId());

        }
        childUser = new ArrayList<User>();
        userList2 = null;
        return JSONUtils.getRoot(0,"success","");
    }


    //更新代理下面用户的二维码
public void setQrCode(long uid){

    new Thread(new Runnable() {
        @Override
        public void run() {
            logger.info("===========uid:"+uid+"============更新代理下面用户的二维码==============================");
            User needQR = iFootUserService.getUserByUid(uid);
            String shareUrl = null;
            try {
                shareUrl = StaticValue.WX.ENTER_URL+"parentID=" + needQR.getId() + "&proxyID=" + needQR.getProxyId();
                logger.info("shareUrl : " + shareUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info("这是测试登录:  QRCode=" + shareUrl);
            String SB = imageUtils.GetQR_BASE64(shareUrl);
//                    logger.info(SB);
            needQR.setQrCode(SB);
            iFootUserService.updateUser(needQR);//更新一下二维码图片 完成注册操作
        }
    }).start();




}



    /**
     * 获取某个父节点下面的所有子节点
     * @param userList
     * @param pid
     * @return
     */
    public  List<User> treeUserList( List<User> userList, Long pid){

        for (User user: userList) {
            //遍历出父id等于参数的id，add进子节点集合
            if(user.getParentId()==pid && user.getProxyId()!=user.getId()){
                logger.info("add user for id : "+user.getId());
                treeUserList(userList,user.getId());
                childUser.add(user);
            }
        }

//        for(User user : userList){
//        for (int i = 0 ;i<userList.size();i++){
//            //遍历出父id等于参数的id，add进子节点集合 && userList.get(i).getProxyId()!=userList.get(i).getId()
//            if(userList.get(i).getParentId() == pid && userList.get(i).getProxyId()!=userList.get(i).getId()){
//                childUser.add(userList.get(i));
//                System.out.println("add user for id : "+userList.get(i).getId());
//                //递归遍历下一级
//                treeUserList(userList,userList.get(i).getId());
//
////            //遍历出父id等于参数的id，add进子节点集合
////            if(userList.get(i).getParentId() == pid){
////                User user = userList.get(i);
//////                userList.remove(i);
////                childUser.add(user);
////                System.out.println(user.getId());
////                //递归遍历下一级
////                treeUserList(userList,user.getId());
//
//
//            }
//        }
        return childUser;
    }




//    /**
//     * 修改所有粉丝的代理id为指定id
//     * @param uid
//     * @param session
//     * @return
//     */
//   @RequestMapping(value = "changProxyId", method = RequestMethod.POST)
//    public JSONObject changProxyId(@RequestParam long uid, HttpSession session) {
//
//        System.out.println(uid+"============");
//        List<User> userList = iFootUserService.getAllUser();
//
//        List<User> userList2 = treeUserList(userList,uid);
//
//        for (int i = 0;i < userList2.size();i++){
//
//            User user = userList2.get(i);
//
//            user.setProxyId(uid);
//
//            iUserFootDAO.updateProxyId(user.getId(),uid);
//
//            System.out.println(user.getId());
//
//        }
//        userList2 = null;
//        //更新
//
//        return JSONUtils.getRoot(0,"success","");
//    }




}
